const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
// 文件上传中间件
const { upload } = require('@/middleware/upload.middleware')
const { sendResponse, clearTempFolder } = require('@/utils/tool')

/** 
 * @swagger
 * /upload:
 *   post:
 *     tags:
 *      - 文件管理
 *     summary: 文件上传
 *     description: 上传一个文件，并指定文件类型。
 *     consumes:
 *       - multipart/form-data
 *     requestBody:
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               file:
 *                 type: string
 *                 format: binary
 *               type:
 *                 type: string
 *                 enum:
 *                   - image
 *                   - video
 *                   - application
 *                   - audio
 *                 description: 文件类型，可选值：image 图片、video 视频、application 文档文件压缩文件等（word、excel、ppt、pdf、text、zip、rar、7z等）、audio 音频。
 *             required:
 *              - file
 *              - type
 *     responses:
 *       '200':
 *         description: 上传成功
 *       '400':
 *         description: 上传失败
*/

// 图片:
// image/jpeg (JPEG/JPG)
// image/png (PNG)
// image/gif (GIF)
// image/svg+xml (SVG)
// 视频:
// video/mp4 (MP4)
// video/x-msvideo (AVI)
// video/mpeg (MPEG)
// video/quicktime (MOV)
// video/x-matroska (MKV)
// 文档:
// application/pdf (PDF)
// application/msword (DOC)
// application/vnd.openxmlformats-officedocument.wordprocessingml.document (DOCX)
// application/vnd.ms-excel (XLS)
// application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (XLSX)
// application/vnd.ms-powerpoint (PPT)
// application/vnd.openxmlformats-officedocument.presentationml.presentation (PPTX)
// text/plain (TXT)
// 压缩文件:
// application/zip (ZIP)
// application/x-tar (TAR)
// application/x-gzip (GZ/GZIP)
// application/x-bzip2 (BZ2)
// 音频:
// audio/mpeg (MP3)
// audio/wav (WAV)
// audio/aac (AAC)
// audio/ogg (OGG)
// audio/flac (FLAC)
router.post('/upload', upload.single('file'), (req, res) => {
  const type = req.body.type;
  const fileType = req.file.mimetype;
  let targetPath;

  // 根据 type 参数决定目标路径
  if (type === 'image' && fileType.includes('image')) {
    targetPath = 'static/images';
  } else if (type === 'video' && fileType.includes('video')) {
    targetPath = 'static/videos';
  } else if (type === 'application' && fileType.includes('application') || fileType.includes('text')) {
    targetPath = 'static/application';
  } else if (type === 'audio' && fileType.includes('audio')) {
    targetPath = 'static/audio';
  } else {
    return sendResponse(req, res, {
      message: 'type类型不存在或与匹配文件类型错误',
      code: 400,
    })
  }

  // 检查目标文件夹是否存在，不存在则创建
  if (!fs.existsSync(targetPath)) {
    fs.mkdirSync(targetPath, { recursive: true });
  }

  // 将文件移动到指定的文件夹
  const fileName = req.file.filename
  const tempFilePath = path.join('static/temp', fileName);
  const newFilePath = path.join(targetPath, fileName);
  fs.rename(tempFilePath, newFilePath, (err) => {
    if (err) {
      return sendResponse(req, res, {
        message: '文件上传失败',
        code: 500
      })
    }
    return sendResponse(req, res, {
      message: '文件上传成功',
      code: 200,
      data: {
        filePath: `/${targetPath}/${fileName}`, // 返回文件路径
        fileType: type,        // 返回文件类型
        size: req.file.size,   // 文件大小
      },
    })
  });
});



/**
 * @swagger
 * /cleartemp:
 *   delete:
 *     tags:
 *      - 文件管理
 *     summary: 清空临时文件夹
 *     description: 清空临时文件夹，用于清理上传过程中产生的临时文件。
 *     security:
 *       - authorization: []
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               password:
 *                 type: string
 *                 description: 管理员密码，用于验证身份。
 *             required:
 *               - password
 *     responses:
 *       '200':
 *         description: 清空成功
 *       '401':
 *         description: 密码错误
 *       '500':
 *         description: 清空失败
 */
router.delete('/cleartemp', async (req, res) => {
  try {
    if (req.body.password === process.env.ADMIN_PASSWORD) {
      let resInfo = await clearTempFolder();
      return sendResponse(req, res, resInfo)
    } else {
      return sendResponse(req, res, {
        message: '密码错误',
        code: 401
      })
    }
  } catch (error) {
    next(error);
  }
});

module.exports = router;